package com.djx.elasticsearch.service;

import com.djx.elasticsearch.entity.DocBean;
import com.djx.elasticsearch.mapper.DocBeanRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

/**
 * @author PACTERA-468
 */
@Service
public class DocBeanService {

    @Autowired
    ElasticsearchRestTemplate restTemplate;

    @Autowired
    DocBeanRepository docBeanRepository;

    private Pageable pageable = PageRequest.of(0,10);

    public void createIndex() {
        restTemplate.save(DocBean.class);
    }

    public void deleteIndex(String index) {
        restTemplate.delete(index, DocBean.class);
    }

    public void save(DocBean docBean) {
        docBeanRepository.save(docBean);
    }

    public void saveAll(List<DocBean> list) {
        docBeanRepository.saveAll(list);
    }

    public Iterator<DocBean> findAll() {
        return docBeanRepository.findAll().iterator();
    }

    public Page<DocBean> findByContent(String content) {
        return docBeanRepository.findByContent(content,pageable);
    }

    public Page<DocBean> findByFirstCode(String firstCode) {
        return docBeanRepository.findByFirstCode(firstCode,pageable);
    }

    public Page<DocBean> findBySecordCode(String secordCode) {
        return docBeanRepository.findBySecordCode(secordCode,pageable);
    }

    public Page<DocBean> query(String key) {
        return docBeanRepository.findByContent(key,pageable);
    }

    public DocBean getById(String id) {
        return restTemplate.get(id, DocBean.class);
    }

}
